package com.lion.httpapi.thread;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPool {
	private ThreadPoolExecutor threadPool;

	public ThreadPool() {
		this(0);
	}

	public ThreadPool(Integer maxSize) {
		if(maxSize>0){
			threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(maxSize);
		}else{
			threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		}
	}

	public boolean execute(Runnable run) {
		try {
			if(isFull()){
				return false;
			}else{
				threadPool.submit(run);
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	public boolean isFull(){
		return getActiveCount()>=threadPool.getMaximumPoolSize();
	}

	public int getActiveCount() {
		return threadPool.getActiveCount();
	}

	public long getCompletedTaskCount() {
		return threadPool.getCompletedTaskCount();
	}

	public void shutdown() {
		threadPool.shutdown();
	}

}
